vim9script noclear

var trigger = v:true

def GetFiles(str: string): list<dict<any>>
	var files: list<dict<any>>
	var dirs: list<dict<any>>
	var dir = expand(str)

	if !isdirectory(dir)
		return []
	endif

	for file in readdir(dir)
		if isdirectory($"{dir}/{file}")
			dirs->add({
				menu: '[dir]', word: file, abbr: $"{file}/", icase: 1
			})
		else
			files->add({
				menu: '[file]', word: file, abbr: file, icase: 1
			})
		endif
	endfor

	return dirs + files
enddef

def GetPrefix(str: string, pat: string): number
	var x: number
	var y: number = matchend(str, pat)

	while y > -1
		x = y
		y = matchend(str, pat, x)
	endwhile

	return x
enddef

export def Start()
	var idx: number
	var files: list<dict<any>>
	var col = col('.') - 2
	var dir: string = getline('.')[ : col]

	idx = GetPrefix(dir, "[\<Space>\<Tab>={}'\"`]")
	dir = dir[idx : ]

	idx = strridx(dir, '/')
	if idx == -1
		col -= len(dir)
		dir = '.'
	else
		col -= len(dir) - idx - 1
		dir = dir[ : idx]
	endif

	files = GetFiles(dir)
	if files->empty()
		return
	endif

	complete(col + 2, files)
enddef

export def Run()
	if trigger
		setlocal iskeyword+=.,-
		augroup PathGroup
			au!
			au CursorMovedI * Start()
		augroup END
		Start()
	else
		setlocal iskeyword-=.,-
		augroup PathGroup
			au!
		augroup END
	endif

	trigger = !trigger
enddef
